package com.lottery.service.pc28.lobbyService.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.dao.pc28.accoutDao.WebNocticeDao;
import com.lottery.dao.pc28.lobbyDao.ImportantNocticeDao;
import com.lottery.dao.pc28.lobbyDao.NoticeDao;
import com.lottery.dto.NoticeVo;
import com.lottery.dto.PageDto;
import com.lottery.dto.ResultDto;
import com.lottery.entity.ImportantNotice;
import com.lottery.entity.Notice;
import com.lottery.entity.WebNotice;
import com.lottery.service.pc28.JedisClient;
import com.lottery.service.pc28.lobbyService.NoticeService;
import com.lottery.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

//系统公告Service

@Service
@Transactional
public class NoticeServiceImpl implements NoticeService {

	@Autowired
	private NoticeDao noticeDao;
	@Autowired
	private JedisClient jedisClient;

	@Autowired
	private WebNocticeDao webNoticeDao;

	@Autowired
	private ImportantNocticeDao importantNocticeDao;

	// 您于
	@Value("${BETTING_BEFORE}")
	private String BETTING_BEFORE;
	// 成功投注.
	@Value("${BETTING_AFTER}")
	private String BETTING_AFTER;
	// 第
	@Value("${LOTTERY_BEFORE}")
	private String LOTTERY_BEFORE;
	// 已开奖,请去主页查看开奖号码!
	@Value("${LOTTERY_AFTER}")
	private String LOTTERY_AFTER;
	// 您于
	@Value("${TRANSFER1_BEFORE}")
	private String TRANSFER1_BEFORE;
	// 充值成功!充值金额:
	@Value("${TRANSFER1_AFTER}")
	private String TRANSFER1_AFTER;
	// 您于
	@Value("${TRANSFER2_BEFORE}")
	private String TRANSFER2_BEFORE;
	// 提现成功!提现金额:
	@Value("${TRANSFER2_AFTER}")
	private String TRANSFER2_AFTER;
	// 您购买的
	@Value("${TRANSFER3_BEFORE}")
	private String TRANSFER3_BEFORE;
	// 期彩票中奖啦!中奖金额:
	@Value("${TRANSFER3_AFTER}")
	private String TRANSFER3_AFTER;
	// redis的notice前缀
	@Value("${NOTICE}")
	private String NOTICE;

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 查询公告信息
	 * 
	 * @return
	 */
	public ResultDto<PageDto> selectAllNotice(int pageNow) {
		ResultDto<PageDto> resultDto = new ResultDto<PageDto>();
		PageDto pageDto = new PageDto();
		int pageSize = 10;
		int totalCount = 0;
		try {
			totalCount = noticeDao.selectNoticeCount();
		} catch (Exception e) {
			resultDto.setSuccess(false);
			return resultDto;
		}

		int totalPageCount = (totalCount + pageSize - 1) / pageSize;
		int startPage = (pageNow - 1) * pageSize;
		pageDto.setPageSize(pageSize);
		pageDto.setPageNow(pageNow);
		pageDto.setstartPage(startPage);
		pageDto.setTotalCount(totalCount);
		pageDto.setTotalPageCount(totalPageCount);
		resultDto.setData(pageDto);

		try {
			List<Notice> selectAllNotice = noticeDao.selectAllNotice(pageDto);
			for (int i = 0; i < selectAllNotice.size(); i++) {
				String noticeInfo = selectAllNotice.get(i).getNoticeInfo();
				if (noticeInfo.length() > 30) {
					selectAllNotice.get(i).setNoticeInfo(noticeInfo.substring(0, 30) + "...");
				}
			}
			resultDto.setList(selectAllNotice);
			resultDto.setSuccess(true);
		} catch (Exception e) {
			logger.error("selectAllNotice error:", e);
			resultDto.setSuccess(false);
		}
		return resultDto;
	}

	/**
	 * 后台管理员插入系统公告
	 * 
	 * @param NoticeInfo
	 *            要插入的公告
	 * @return
	 */
	public ResultDto<Notice> adminInsertNotice(String noticeInfo) {
		ResultDto<Notice> resultDto = new ResultDto<Notice>();
		Notice notice = new Notice();
		notice.setNoticeDate(new Date());
		notice.setUserId(0); // 管理员发布公告默认 user_id=0
		notice.setNoticeInfo(noticeInfo);
		try {
			noticeDao.insertNotice(notice);
			resultDto.setSuccess(true);
		} catch (Exception e) {
			logger.error("adminInsertNotice error:", e);
			resultDto.setSuccess(false);
		}
		return resultDto;
	}

	/**
	 * 删除公告信息
	 * 
	 * @param id
	 * @return
	 */
	public ResultDto<Notice> deleteNotice(int id) {
		ResultDto<Notice> resultDto = new ResultDto<Notice>();
		Notice notice = new Notice();
		notice.setId(id);
		notice.setUserId(1);
		try {
			noticeDao.updateNotice(notice);
			resultDto.setSuccess(true);
		} catch (Exception e) {
			logger.error("deleteNotice error:", e);
			resultDto.setSuccess(false);
		}
		return resultDto;
	}

	/**
	 * 修改公告信息
	 * 
	 * @param id
	 * @param noticeInfo
	 * @return
	 */
	public ResultDto<Notice> editNotice(int id, String noticeInfo) {
		ResultDto<Notice> resultDto = new ResultDto<Notice>();
		Notice notice = new Notice();
		notice.setNoticeDate(new Date());
		notice.setUserId(0); // 管理员发布公告默认 user_id=0
		notice.setNoticeInfo(noticeInfo);

		Notice denotice = new Notice();
		denotice.setId(id);
		denotice.setUserId(1);

		try {
			noticeDao.insertNotice(notice);
			noticeDao.updateNotice(denotice);
			resultDto.setSuccess(true);
		} catch (Exception e) {
			logger.error("editNotice error:", e);
			resultDto.setSuccess(false);
		}
		return resultDto;
	}

	/**
	 * 返回最近不重复的最多20条公告
	 * 
	 * @param userId
	 * @return
	 */
	public String queryNotice(int userId) {
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<Notice> subList = new ArrayList<>();
		try {
			// 从redis中获取当前用户上次获取公告 的最大id
			String string = jedisClient.get(NOTICE + userId);
			// 当前用户第一次登录
			if (string == null) {
				// 获得最近的一条系统公告
				NoticeVo noticeVo = new NoticeVo(0, userId);
				Notice notice = noticeDao.selectNoticeByUser(noticeVo);
				// if (list != null && list.size() != 0) {
				// subList = list.subList(0, 1);
				// }
				if (notice != null) {
					subList.add(notice);
				}

			} else {
				// 当前用户不是第一次登录,获得最近未获取的的最多20条公告
				int parseInt = Integer.parseInt(string);
				NoticeVo noticeVo = new NoticeVo(parseInt, userId);
				Notice notice = noticeDao.selectNoticeByUser(noticeVo);
				if (notice != null) {
					subList.add(notice);
				}
			}
			if (subList.size() > 0) {
				jedisClient.set(NOTICE + userId, subList.get(0).getId() + "");
			}
			maxmap.put("array", subList);
			maxmap.put("result", "0");
			maxmap.put("msg", "获取成功");
			maxmap.put("state", "3");
		} catch (Exception e) {
			logger.error("queryNotice error:", e);
			maxmap.put("result", "1");
			maxmap.put("msg", "获取失败");
		}
		return JSON.toJSONString(maxmap, true);
	}

	@Override
	public ResultDto<Notice> selectOneNotice(int id) {
		ResultDto<Notice> resultDto = new ResultDto<Notice>();
		try {
			Notice selectOneNotice = noticeDao.selectOneNotice(id);
			resultDto.setData(selectOneNotice);
			resultDto.setSuccess(true);
		} catch (Exception e) {
			logger.error("selectOneNotice error:", e);
			resultDto.setSuccess(false);
		}
		return resultDto;
	}

	/**
	 * 增加WEB版公告
	 */

	public ResultDto<WebNotice> insertWebNotice(WebNotice webNotice) {

		ResultDto<WebNotice> resultDto = new ResultDto<WebNotice>();
		try {
			webNotice.setNoticeDate(DateUtil.getFormatDate("yyyy-MM-dd"));
			webNoticeDao.insertWebNotice(webNotice);
			resultDto.setSuccess(true);

		} catch (Exception e) {
			logger.error("insertWebNotice error:", e);
			e.printStackTrace();
			resultDto.setSuccess(false);
		}

		return resultDto;
	}

	@Override
	public ResultDto<WebNotice> findByIdWebNotice(int id) {
		ResultDto<WebNotice> result = new ResultDto<WebNotice>();
		try {
			WebNotice selectId = webNoticeDao.selectId(id);
			result.setData(selectId);
			result.setSuccess(true);
			result.setMessage("点击查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("findByIdWebNotice error:", e);
			result.setSuccess(false);
			result.setMessage("点击查询失败");
		}

		return result;

	}

	/**
	 * 返回最近不重复的最多20条公告
	 * 
	 * @param userId
	 * @return
	 */
	public String queryImportantNotice(int id) {
		JSONObject jObject = new JSONObject();
		try {
			ImportantNotice importantNotice = importantNocticeDao.selectLastNotice(id);
			if (importantNotice != null) {
				jObject.put("id", importantNotice.getId());
				jObject.put("display", importantNotice.getDisplay());
				jObject.put("welcome", importantNotice.getWelcome());
				jObject.put("noticeTitle", importantNotice.getNoticeTitle());
				jObject.put("noticeInfo", importantNotice.getNoticeInfo());
				jObject.put("noticeImportant", importantNotice.getNoticeImportant());
				jObject.put("noticeDate", importantNotice.getNoticeDate());
				jObject.put("remark", importantNotice.getRemark());
			} else {
				jObject.put("display", "0");
			}

			jObject.put("result", "0");
			jObject.put("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			// 返回状态，失败为 1
			jObject.put("result", "1");
			jObject.put("Errmsg", "失败");
			logger.error("queryImportantNotice error:", e);
		}
		return jObject.toJSONString();
	}

	@Override
	public String getAppNotice() {
		// TODO Auto-generated method stub
		Map<String, Object> maxmap = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			List<Notice> noticeList = noticeDao.appSelectNotice();
			for (Notice one : noticeList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("msgid", one.getId());
				map.put("noticeTitle", one.getNoticeTitle());
				map.put("noticeInfo", one.getNoticeInfo());
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String dateStr = df.format(one.getNoticeDate());
				map.put("noticeDate", dateStr);
				map.put("noticeShow", one.getNoticeShow());
				list.add(map);
			}
			maxmap.put("arrayMsg", list);
			maxmap.put("result", "0");
		} catch (Exception e) {
			e.printStackTrace();
			// 返回状态，失败为 1
			maxmap.put("result", "1");
			maxmap.put("ErrMsg", "公告获取失败");
		}
		return JSON.toJSONString(maxmap, true);
	}
}
